package org.ruoyi.interview.config;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.google.gson.*;

/**
 * 讯飞星火Spark Lite API客户端
 */
public class XunfeiSparkClient {
    // 讯飞星火Spark Lite API基础地址 (HTTP)
    private static final String HOST_URL = "https://spark-api-open.xf-yun.com/v1/chat/completions";
    // 你的API密钥相关参数
    private final String appId;
    private final String apiKey;
    private final String apiSecret;

    public XunfeiSparkClient(String appId, String apiKey, String apiSecret) {
        this.appId = appId;
        this.apiKey = apiKey;
        this.apiSecret = apiSecret;
    }


    /**
     * HMAC-SHA256加密
     * @param key 密钥
     * @param message 消息
     * @return 加密结果
     * @throws Exception 加密异常
     */
    private byte[] hmacSha256(String key, String message) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(secretKeySpec);
        return mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 构建带有鉴权信息的Authorization头部
     * @return 鉴权头部值
     * @throws Exception 加密异常
     */
    private String getAuthorizationHeader() throws Exception {
        URL url = new URL(HOST_URL);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());

        String host = url.getHost();
        if (url.getPort() != -1) {
            host += ":" + url.getPort();
        }

        // 构建待签名字符串，必须包含host、date和request-line头部
        StringBuilder builder = new StringBuilder();
        builder.append("host: ").append(host).append("\n");
        builder.append("date: ").append(date).append("\n");
        builder.append("POST ").append(url.getPath()).append(" HTTP/1.1");

        // 使用HmacSHA256算法计算签名
        byte[] shaBytes = hmacSha256(apiSecret, builder.toString());
        String signature = Base64.getEncoder().encodeToString(shaBytes);

        // 构建authorization头部
        String authBase64 = Base64.getEncoder().encodeToString(
            ("api_key=\"" + apiKey + "\", "
             + "algorithm=\"hmac-sha256\", "
             + "headers=\"host date request-line\", "
             + "signature=\"" + signature + "\"").getBytes(StandardCharsets.UTF_8));

        return "hmac " + authBase64;
    }

    /**
     * 构建请求参数
     * @param text 用户输入文本
     * @return 请求参数JSON
     */
    public String buildRequestParams(String text) {
        JsonObject request = new JsonObject();

        // header部分
        JsonObject header = new JsonObject();
        header.addProperty("app_id", appId);
        header.addProperty("uid", "ruoyi_ai_user");
        request.add("header", header);

        // parameter部分
        JsonObject parameter = new JsonObject();
        JsonObject chat = new JsonObject();
        chat.addProperty("domain", "general");
        chat.addProperty("temperature", 0.5);
        chat.addProperty("max_tokens", 1024);
        parameter.add("chat", chat);
        request.add("parameter", parameter);

        // payload部分
        JsonObject payload = new JsonObject();
        JsonObject message = new JsonObject();
        JsonArray textArray = new JsonArray();

        JsonObject inputText = new JsonObject();
        inputText.addProperty("role", "user");
        inputText.addProperty("content", text);
        textArray.add(inputText);

        message.add("text", textArray);
        payload.add("message", message);
        request.add("payload", payload);

        return request.toString();
    }
    
    /**
     * 发送HTTP请求并获取响应
     * @param prompt 用户输入的提示文本
     * @return AI模型的响应内容
     * @throws Exception 网络或解析异常
     */
    public String sendRequest(String prompt) throws Exception {
        // 创建URL对象
        URL url = new URL(HOST_URL);
        
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        // 使用HMAC签名方式认证
        connection.setRequestProperty("Authorization", this.getAuthorizationHeader());
        connection.setDoOutput(true);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(30000);
        
        // 使用 buildRequestParams 构建请求体
        String requestBody = this.buildRequestParams(prompt);
        
        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        // 读取响应
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return parseResponse(response.toString());
            }
        } else {
            // 读取错误响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                throw new Exception("请求失败，HTTP状态码: " + responseCode + "，错误信息: " + response.toString());
            }
        }
    }
    
    /**
     * 解析API响应
     * @param response API响应字符串
     * @return AI回答的内容
     * @throws Exception 解析异常
     */
    private String parseResponse(String response) throws Exception {
        JsonObject responseObject = JsonParser.parseString(response).getAsJsonObject();
        
        // 检查是否有错误
        if (responseObject.has("error")) {
            JsonObject error = responseObject.getAsJsonObject("error");
            String message = error.has("message") ? error.get("message").getAsString() : "未知错误";
            throw new Exception("API返回错误: " + message);
        }
        
        // 提取回答内容
        if (responseObject.has("choices")) {
            JsonArray choices = responseObject.getAsJsonArray("choices");
            if (choices.size() > 0) {
                JsonObject choice = choices.get(0).getAsJsonObject();
                if (choice.has("message")) {
                    JsonObject message = choice.getAsJsonObject("message");
                    if (message.has("content")) {
                        return message.get("content").getAsString();
                    }
                }
            }
        }
        
        throw new Exception("无法从响应中提取回答内容: " + response);
    }

    // 使用示例
    public static void main(String[] args) {
        // 替换为你的实际参数
        String appId = "a97779c4";
        String apiKey = "b58d59abdfd5c502e0151a0ab1d92247";
        String apiSecret = "ZDlmYzQ2NzYyYzNkYjMwY2Y5Y2ZhMjlh";

        XunfeiSparkClient client = new XunfeiSparkClient(appId, apiKey, apiSecret);

        try {
            // 发送请求并获取响应
            String response = client.sendRequest("请介绍一下人工智能的发展历程");
            System.out.println("AI回答: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}